<?php

// +----------------------------------------------------------------------

// | Description: 客户

// +----------------------------------------------------------------------

// | Author: zl

// +----------------------------------------------------------------------



namespace app\crm\controller;



use app\admin\controller\ApiCommon;

use app\crm\model\BalanceLog;

use app\crm\model\Setting;

use app\crm\model\SettingCategory;

use app\crm\model\Service;

use app\crm\model\ReturnVist;

use app\crm\model\ReturnVistT;

use app\crm\model\Customer as CustomerModel;

use app\crm\model\TransferShop;

use app\crm\model\CustomerConfig as CustomerConfigModel;

use app\crm\model\CustomerGrade as CustomerGradeModel;

use think\response\Json;

use think\facade\Db;



class Customer2 extends ApiCommon

{

    protected $customerModel;

    protected $customerConfigModel;

    /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @other 其他根据系统设置

     **/

    public function initialize()

    {

        $action = [

            'permission' => ['daoruitem','daorugoods','house_list','setcustomerage','setzycustomer','daoru','daorubahen','daorukaxiang','daoruyue','daorujindiebianma','zengjiayue','savek3andyue1','savek3andyue2','kaxianggengxin','getshop','getshopdel','daorukaxiang2','daorushezhihuiyuan','getshezhihuiyuan','shezhihuiyuan','daoruchengjiao','getshezhichengjiao','shezhichengjiao','getgengxinxiangce','daorugengxinxiangce','shezhigengxinxiangce','daochuchengjiaokehu','daoruanli','daochutianjia','daochujindian','kehuInfoUpdate','gengxinnianling','serviceCardList'],

            'allow' => ['users', 'info']

        ];

        event('CheckAuth',$action);

        $request = $this->request;

        $a = strtolower($request->action());



        $this->customerModel = new CustomerModel();

        $this->customerConfigModel = new CustomerConfigModel();

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }


    public function daoruitem(){

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';




        $addData = [];

        foreach ($importData as $key => $val){

            $one = [];
            $one['name'] = $val[3];
            $one['kingdee_code'] = $val[4];
            $one['unit_code'] =  $val[6];
            $one['unit_name'] = $val[5];
            $one['standard_price'] = $val[7];

            $one['type_one'] =  DB::name('item_type')->where('pid',0)->where('name',$val[0])->value('id');
            $one['type_two'] =  DB::name('item_type')->where('pid',$one['type_one'])->where('level',2)->where('name',$val[1])->value('id');
            $one['type_three'] = DB::name('item_type')->where('pid',$one['type_two'])->where('level',3)->where('name',$val[2])->value('id');

            $one['create_time'] = time();


            array_push($addData,$one);

        }

        // print_r($addData);exit;

        if(count($addData) != count($importData)){

            echo('需要入库的数据缺失，请先处理异常数据。[可以入库的数据：'.count($addData).'条，不等于总计需要入库：'.count($importData).'条]<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');exit;

        }

        if(empty($addData)){

            echo('需要入库的数据为空<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');exit;

        }

        $res = 0;


        $res = Db::name("product_item")->insertAll($addData);

        print_r('可以入库的数据:'.count($addData).'条');

        print_r('-');

        print_r('成功入库：'.$res.'条<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');

        exit;





    }



    public function daorugoods(){


        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';



        $hanzi = [
            '支'=>'zhi',
            '盒'=>'he',
            '本'=>'ben',
            '瓶'=>'ping',
            '套'=>'tao',
            '个'=>'ge',
            '袋'=>'dai',
            '包'=>'bao',
            '张'=>'zhang',
            '贴'=>'tie',
            'pcs'=>'pcs',
            '桶'=>'tong'
        ];

        $addData = [];

        foreach ($importData as $key => $val){

            $one = [];

            $one['name'] = $val[1];

            $one['category_id'] = 1;

            $one['kingdee_code'] = $val[0];

            $one['spec_name'] = $val[2];

            $one['unit_code'] =  $hanzi[$val[3]]??'';

            $one['unit_name'] = $val[3];


            $one['is_project'] = 4;

            $one['status'] = 1;

            $one['create_time'] = time();



            array_push($addData,$one);

        }

//         print_r($addData);exit;

        if(count($addData) != count($importData)){

            echo('需要入库的数据缺失，请先处理异常数据。[可以入库的数据：'.count($addData).'条，不等于总计需要入库：'.count($importData).'条]<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');exit;

        }

        if(empty($addData)){

            echo('需要入库的数据为空<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');exit;

        }

        $res = 0;

        $res = Db::name("shop_goods")->insertAll($addData);

        print_r('可以入库的数据:'.count($addData).'条');

        print_r('-');

        print_r('成功入库：'.$res.'条<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');

        exit;





    }



    /**

     * 处理直营店客户的余额数据

     */

    public function daoru()

    {

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/huiyuan.html">返回【会员基本信息导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/huiyuan.html">返回【会员基本信息导入】页面</a>';exit;

        }

       /* print_r($_FILES['file']);

        exit; */

        $importData = readExcelData($tmp_name);

        echo '<pre>';

        //print_r($importData);exit;





        //----更新已经导入的客户录入时间和性别信息--2022-03-05

        foreach ($importData as $key => $val){



            $save=[];



            $save=[

                 'nurse_id'=>$val[1]

                ];

            $res = Db::name('customer')->where('id','=',$val[0])->update($save);
            //$res = Db::name('customer')->where('id','=',$val[0])->update($save);

        }

        /* echo '进入---555555555555';

        exit; */



        echo '表格中共计：'.count($importData).'条记录<br><br>';

        //exit;

        // unset($importData[0]);

        $new = array();

        // foreach($importData as $key => $val){

        //     $one = [];

        //     foreach ($val as $k =>$v){

        //         if(empty($v)){

        //             break;

        //         }

        //         $one[$k] = trim($v);

        //     }

        //     if(empty($one)){

        //         continue;

        //     }

        //     array_push($new,$one);

        // }

        // $importData = $new;

        // Db::name("customer")->where('id','>=',166)->delete();

        // Db::name("customer_scar")->where('customer_id','>=',166)->delete();

        // exit;

        // print_r(count($importData));

        // print_r('-');

        $importData = array_values($importData);

        $addData = [];

        $inWhere = array_values(array_unique(array_column($importData,'1')));

        $cunzaiShoujihao = Db::name("customer")->where('telephone','in',$inWhere)->column('telephone');

        //获取店铺数据

        $shopNameList = array_values(array_unique(array_column($importData,'4')));

		//print_r($shopNameList);exit;

        $shopList = Db::name("shop")->where('shop_name','in',$shopNameList)->column('shop_id','shop_name');

        //获取员工数据

        $shopPersonNameList = array_values(array_unique(array_column($importData,'20')));

        $shopIds = array_values($shopList);

        $where = [];

        array_push($where,['name','in',$shopPersonNameList]);

        array_push($where,['shop_id','in',$shopIds]);

        // print_r($where);exit;

        $shopPersonList = Db::name("shop_person")->where($where)->column('id,shop_name,name,shop_id');

        // print_r($shopList);exit;

        //客户来源数据

        $sourceNameList = array_values(array_unique(array_column($importData,'15')));

        $where = [];

        // array_push($where,['name','in',$sourceNameList]);

        array_push($where,['category_id','=',4]);

        $sourceList = Db::name("setting")->where($where)->column('id','name');

        //修复状态

        $zhuangtaiNameList = array_values(array_unique(array_column($importData,'21')));

        $where = [];

        // array_push($where,['name','in',$zhuangtaiNameList]);

        array_push($where,['category_id','=',5]);

        $zhuangtaiList = Db::name("setting")->where($where)->column('id','name');

        //创建人id

        $kefuNameList = array_values(array_unique(array_column($importData,'19')));

        $where = [];

        array_push($where,['realname','in',$kefuNameList]);

        $creatorList = Db::name("admin_user")->where($where)->column('id','realname');

        // print_r($shopPersonList);exit;

        // 性别数据

        $sex = ['男'=>1,'女'=>2,''=>0];

        // print_r(count($importData));

        // print_r('-');

        // exit;

        foreach ($importData as $key => $val){

            if(!empty($cunzaiShoujihao) && in_array($val[1],$cunzaiShoujihao)){

                echo('客户手机号:'.$val[1].'--已在数据库中存在<br>');

                continue;

            }

            // print_r($val);exit;

            $shop_id = $shopList[$val[4]] ?? '';

            if (empty($shop_id)) {

                // code...

                echo('客户手机号:'.$val[1].'--对应的店铺数据不存在<br>');

                continue;

            }

            $nurse_id = 0;

            if(!empty($val[20])){

                foreach ($shopPersonList as $k1 => $v1){

                    if($shop_id == $v1['shop_id'] && $v1['name'] == $val[20]){

                        $nurse_id = $v1['id'];

                    }

                }

                if(empty($nurse_id)){

                    echo('客户手机号:'.$val[1].'--对应的护理师数据不存在<br>');

                    continue;

                }

            }

            $creator_id = 1;

            if(!empty($val[19])){

                $creator_id = $creatorList[$val[19]] ?? 0;

                if(empty($creator_id)){

                    echo('客户手机号:'.$val[1].'--所属对应的客服数据不存在<br>');

                    continue;

                }

            }

            $val[15] = empty($val[15]) ? '门头' : $val[15];

            $source_id = $sourceList[$val[15]] ?? '';

            if(empty($source_id)){

                echo('上传终止，客户手机号:'.$val[1].'客户来源不存在，请先添加客户来源:'.$val[15].'<br><br><br><a href="http://sunburn.178590.com/return/huiyuan.html">返回【会员基本信息导入】页面</a>');

                exit;

            }

            $val[21] = empty($val[21]) ? '新客户' : $val[21];

            $repair_progress = $zhuangtaiList[$val[21]] ?? '';

            if (empty($repair_progress)) {

                // code...

                echo('上传终止，客户手机号:'.$val[1].'修复进展不存在，请先添加修复进展:'.$val[21].'<br><br><br><a href="http://sunburn.178590.com/return/huiyuan.html">返回【会员基本信息导入】页面</a>');

                exit;

            }

            $oneData = [];

            $oneData['shop_id']         = $shop_id;

            $oneData['customer_name']   = $val[0];

            $oneData['telephone']       = intval($val[1]);

            $oneData['sex']             = $sex[$val[5]] ?? 0;

            $oneData['birthday']        = empty($val[6]) ? 0 : strtotime($val[6]);

            //$oneData['age']             = empty($oneData['birthday']) ? : bcsub(date('Y'),date('Y',$oneData['birthday']));
			$oneData['age']             = intval($val[13]);

                    // $oneData['province']        = '';

                    // $oneData['city']            = '';

                    // $oneData['region']          = '';

                    // $oneData['detailed_address']= '';

            $oneData['first_time']      = empty($val[12]) ? 0 : strtotime($val[12]);

            $oneData['effective_entry'] = empty($oneData['first_time']) ? 2 : 1;

            //$oneData['second_time']     = empty($val[13]) ? 0 : strtotime($val[13]);

			//$oneData['second_time']     = '0';

            $oneData['create_time']     = empty($val[12]) ? 0 : strtotime($val[12]);

            $oneData['update_time']     = empty($val[12]) ? 0 : strtotime($val[12]);

            $oneData['status']          = 1;

            $oneData['source_id']       = $source_id;

            $oneData['creator_id']      = $creator_id;

            $oneData['nurse_id']        = $nurse_id;

            $oneData['repair_progress'] = $repair_progress;

                    // $oneData['member_label']    = '';

                    // $oneData['member_classification'] = '';

            //$oneData['consumption']     = $val[3];      // 累计消费金额

            $oneData['operator']        = $oneData['creator_id'];

            array_push($addData,$oneData);

        }

		/* echo '<pre>';
		print_r($addData);exit; */

        if(count($addData) != count($importData)){

            echo('需要入库的数据缺失，请先处理异常数据。[可以入库的数据：'.count($addData).'条，不等于总计需要入库：'.count($importData).'条]<br><br><a href="http://sunburn.178590.com/return/huiyuan.html">返回【会员基本信息-疤痕导入】页面</a>');exit;

        }

        if(empty($addData)){

            echo('需要入库的数据为空<br><br><a href="http://sunburn.178590.com/return/huiyuan.html">返回【会员基本信息-疤痕导入】页面</a>');exit;

        }

        $res = 0;

        $res = Db::name("customer")->insertAll($addData);

        print_r('可以入库的数据:'.count($addData).'条');

        print_r('-');

        print_r('成功入库：'.$res.'条<br><br><a href="http://sunburn.178590.com/return/huiyuan.html">返回【会员基本信息导入】页面</a>');

        // print_r('-');

        // print_r(count($cunzaiShoujihao));

        exit;

    }

     public function daorubahen()

    {

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/bahen.html">返回【会员基本信息-疤痕导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/bahen.html">返回【会员基本信息-疤痕导入】页面</a>';exit;

        }



        // print_r(111);

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        //客户id

        $phoneList = array_values(array_unique(array_column($importData,'1')));

        foreach ($phoneList as $key => $val){

            $phoneList[$key] = intval($val);

        }

        $where = [];

        array_push($where,['telephone','in',$phoneList]);

        // array_push($where,['shop_id','in',['73782775392774','73782775377728','73782775085647','73782774881835']]);

        $customerList = Db::name("customer")->where($where)->column('id','telephone');

        //疤痕类型

        $bahenList = array_values(array_unique(array_column($importData,'22')));

        $where = [];

        array_push($where,['name','in',$bahenList]);

        array_push($where,['category_id','=',1]);

        $settingList = Db::name("setting")->where($where)->column('id','name');

        $addData = [];

        // print_r(count($customerList));

        foreach ($importData as $key => $val){

            $phone = intval($val[1]);

            $customer_id = $customerList[$phone] ?? '';

            // var_dump($customerList);exit();

            if(empty($customer_id)){

                echo('客户手机号:'.$val[1].'--客户数据没有入库<br>');

                continue;

            }

            if(empty($val[22])){

                continue;

            }

            $find = Db::name("customer_scar")->where('customer_id','=',$customer_id)->find();

            if(!empty($find)){

                echo('客户手机号:'.$val[1].'--客户疤痕数据已入库<br>');

                continue;

            }

            $banhenid = $settingList[$val[22]] ?? '';

            if(empty($banhenid)){

                echo('上传终止，客户手机号:'.$val[1].'疤痕类型不存在，请先添加疤痕类型:'.$val[15].'<br><br><br><a href="http://sunburn.178590.com/return/bahen.html">返回【会员基本信息-疤痕导入】页面</a>');

                exit;

            }

            $one = [];

            $one['customer_setting_id_position'] = 13;

            $one['customer_setting_id_type'] = $banhenid;

            $one['customer_id'] = $customer_id;

            array_push($addData,$one);

        }

        if(count($addData) != count($importData)){

            echo('需要入库的数据缺失，请先处理异常数据。[可以入库的数据：'.count($addData).'条，不等于总计需要入库：'.count($importData).'条]<br><br><a href="http://sunburn.178590.com/return/bahen.html">返回【会员基本信息-疤痕导入】页面</a>');exit;

        }

        if(empty($addData)){

            echo('需要入库的数据为空<br><br><a href="http://sunburn.178590.com/return/bahen.html">返回【会员基本信息-疤痕导入】页面</a>');exit;

        }

        $res = 0;

        $res = Db::name("customer_scar")->insertAll($addData);

        print_r('可以入库的数据:'.count($addData).'条');

        print_r('-');

        print_r('成功入库：'.$res.'条<br><br><a href="http://sunburn.178590.com/return/bahen.html">返回【会员基本信息-疤痕导入】页面</a>');

        exit;

    }

    public function daorukaxiang()

    {

       if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        //客户id

        $phoneList = array_values(array_unique(array_column($importData,'1')));

        foreach ($phoneList as $key => $val){

            $phoneList[$key] = intval($val);

        }

        //获取员工数据

        $shopPersonNameList = array_values(array_unique(array_column($importData,'8')));

        $where = [];

        array_push($where,['name','in',$shopPersonNameList]);

        $shopPersonList = Db::name("shop_person")->where($where)->column('id','name');

        $where = [];

        array_push($where,['telephone','in',$phoneList]);

        // array_push($where,['shop_id','in',['73782775392774','73782775377728','73782775085647','73782774881835']]);

        $customerList = Db::name("customer")->where($where)->column('id,shop_id','telephone');

        // print_r(count($phoneList));

        $addData = [];

        foreach ($importData as $key => $val){

            $phone = intval($val[1]);

            $customerInfo = $customerList[$phone] ?? [];

            if(empty($customerInfo)){

                echo('客户手机号:'.$val[1].'--客户数据没有入库<br>');

                continue;

            }

            $shopPerson = $shopPersonList[$val[8]] ?? 0;

            if(empty($shopPerson)){

                echo('客户手机号:'.$val[1].'--客户的开卡人数据不存在<br>');

                continue;

            }

            $customer_id = $customerInfo['id'];

            $shop_id = $customerInfo['shop_id'];

            $one = [];

            $one['name'] = $val[3];

            $one['shop_id'] = $shop_id;

            $one['customer_id'] = $customer_id;

            $one['service_type'] = $val[5] == '按次' ? 2: 1;

            if($one['service_type'] == 2){

                $one['num'] = $val[6];

                $one['start_time'] = 0;

                $one['end_time'] = 0;

            }else{

                $one['num'] = 0;

                $one['start_time'] = time();

                $one['end_time'] = intval(strtotime($val[7].' 00:00:00'));

            }

            $one['create_time'] = strtotime($val[0].' 00:00:00');

            $one['last_service_time'] = 0;

            $one['status'] = 1;

            $one['experience'] = 0;

            $one['kk_user_id'] = $shopPerson;

            $one['kk_money'] = 0;

            array_push($addData,$one);

        }

        // print_r($addData);exit;

        if(count($addData) != count($importData)){

            echo('需要入库的数据缺失，请先处理异常数据。[可以入库的数据：'.count($addData).'条，不等于总计需要入库：'.count($importData).'条]<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');exit;

        }

        if(empty($addData)){

            echo('需要入库的数据为空<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');exit;

        }

        $res = 0;

        $res = Db::name("service")->insertAll($addData);

        print_r('可以入库的数据:'.count($addData).'条');

        print_r('-');

        print_r('成功入库：'.$res.'条<br><br><a href="http://sunburn.178590.com/return/kaxiang.html">返回【会员基本信息-卡项导入】页面</a>');

        exit;

    }



    public function daoruyue()

    {

       if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/yue.html">返回【会员基本信息-余额导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/yue.html">返回【会员基本信息-余额导入】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        //客户id

        $phoneList = array_values(array_unique(array_column($importData,'1')));

        foreach ($phoneList as $key => $val){

            $phoneList[$key] = intval($val);

        }

        //获取员工数据

        //客户id

        $where = [];

        $phoneList = array_values(array_unique(array_column($importData,'1')));

        foreach ($phoneList as $key => $val){

            $phoneList[$key] = intval($val);

        }

        array_push($where,['telephone','in',$phoneList]);

        // array_push($where,['shop_id','in',['73782775392774','73782775377728','73782775085647','73782774881835']]);

        $customerList = Db::name("customer")->where($where)->column('id,shop_id','telephone');

        $addData = [];

        foreach ($importData as $key => $val){

            $phone = intval($val[1]);

            $customerInfo = $customerList[$phone] ?? [];

            if(empty($customerInfo)){

                echo('客户手机号:'.$val[1].'--客户基本资料数据没有入库<br>');

                continue;

            }

            $customer_id = $customerInfo['id'];

            $shop_id = $customerInfo['shop_id'];

            $a = Db::name("customer_balance")->where('customer_id','=',$customer_id)->find();

            if($a){

                echo('客户手机号:'.$val[1].'--余额数据已入库<br>');

                continue;

            }

            $one = [];

            $one['shop_id'] = $shop_id;

            $one['customer_id'] = $customer_id;

            $one['balance_category_id'] = 1;

            $one['money'] = $val[2] ?? 0;

            $one['complimentary_money'] = $val[3] ?? 0;

            array_push($addData,$one);

            $one = [];

            $one['shop_id'] = $shop_id;

            $one['customer_id'] = $customer_id;

            $one['balance_category_id'] = 2;

            $one['money'] = $val[4] ?? 0;

            $one['complimentary_money'] = $val[5] ?? 0;

            array_push($addData,$one);

        }

        // print_r($addData);exit;

        if(count($addData) != count($importData)*2){

            echo('需要入库的数据缺失，请先处理异常数据。[可以入库的数据：'.count($addData).'条，不等于总计需要入库：'.count($importData).'条]<br><br><a href="http://sunburn.178590.com/return/yue.html">返回【会员基本信息-余额导入】页面</a>');exit;

        }

        if(empty($addData)){

            echo('需要入库的数据为空<br><br><a href="http://sunburn.178590.com/return/yue.html">返回【会员基本信息-余额导入】页面</a>');exit;

        }

        $res = 0;

        $res = Db::name("customer_balance")->insertAll($addData);

        print_r('可以入库的数据:'.count($addData).'条');

        print_r('-');

        print_r('成功入库：'.$res.'条<br><br><a href="http://sunburn.178590.com/return/yue.html">返回【会员基本信息-余额导入】页面</a>');

        exit;

    }



    public function  daorujindiebianma()

    {

        if (empty($_FILES['file'])) {

           echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/k3.html">返回【会员基本信息-k3导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/k3.html">返回【会员基本信息-k3导入】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        // exit;

        // 获取员工数据

        $where = [];

        $phoneList = array_values(array_unique(array_column($importData,'3')));

        // print_r(count($phoneList));

        // print_r('-');

        foreach ($phoneList as $key => $val){

            $phoneList[$key] = intval($val);

        }

        array_push($where,['telephone','in',$phoneList]);

        // array_push($where,['shop_id','in',['73782775392774','73782775377728','73782775085647','73782774881835']]);

        $customerList = Db::name("customer")->where($where)->column('id,shop_id','telephone');

        // print_r(count($customerList));

        // print_r('<br>');

        $name = '客户手机号:';

        $addAll = [];

        $ids = [];

        foreach($importData as $key => $val){

            $info = $customerList[$val[3]] ?? 0;

            // print_r($info);exit;

            if(!empty($info)){

                $id = $info['id'];

                $shop_id = $info['shop_id'];

                $save = [];

                $one = [];

                $save['fcustId'] = $val[0];

                $save['king_no'] = $val[1];

                $res = Db::name("customer")->where('id','=',$id)->update($save);

                if(!$res){

                  echo $name.$val[3].'-金蝶编码编辑失败<br>';

                  continue;

                }

                if(in_array($id,$ids)){

                    continue;

                }

                $one['shop_id'] = $shop_id;

                $one['king_no'] = $val[1];

                $one['fcustId'] = $val[0];

                $one['customer_id'] = $id;

                $res = Db::name("customer_bind")->where('customer_id','=',$id)->find();

                if($res){

                    continue;

                }

                array_push($ids,$id);

                array_push($addAll,$one);

            }else{

                echo $name.$val[3].'-客户基础数据资料不存在<br>';

            }

        }

        // print_r(count($addAll));

        if(empty($addAll)){

            echo('需要入库的数据为空<br><br><a href="http://sunburn.178590.com/return/k3.html">返回【会员基本信息-k3数据导入】页面</a>');exit;

            exit;

        }

        // print_r(count($addAll));

        $res = Db::name("customer_bind")->insertAll($addAll);

        // print_r('--'.$res);

        print_r('更新成功<br><br><a href="http://sunburn.178590.com/return/yue.html">返回【会员基本信息-余额导入】页面</a>');

        exit;

    }

    public function zengjiayue()

    {

        // $name = '辛先生,董女士,长江道,王先生,史女士,张女士,孙女士,王女士,于女士,先生,贾女士,夏先生,赵先生,女士,尹女士,王女士,女士,刘先生,李女士,南吉卉,张女士,廖选红,刘连胜,骆老师,熊建民,陈新虎,陈中英,李彦红,田会欣,曾先生,韦荣业,王蕾,周晓梅,韩龙,叶顺伟,何女士,陈女士,何龙秀,陈志斌,王女士,赵士伟,赵文文,常东海,董文碧,水清澜,王琪,谢先生,马玲琼,钦永辉,冯建木,王先生,梅,刘坤,陈华,韦春利,朱女士,王先生,张女士,黎女士,郭先生,马女士,黄女士,韩秋风,许中席,曹敏,王金朵,张创洋,袁女士,黄志强,涵涵,心田,吴,王万学,牟女士,秦先生,王老师,文方容,于瑞霞,胡德国,许莹莹,张怡琳,苗苗,杨俊丽,刘修世,鲁存香,许成功,史女士,徐女士,黄敬雯,江辉,张生,张云,汉风,胡蓉,李焰,思敏,张婷婷,郑昌玺,唐丽春,黄承晨,冉艳东,罗玉香,刘俊花,于书玲,杨文钊,杨海俪,熊先生,李先生,王明浩,杜伯辟,利先凯,王娜,王晓峰,倪女士,虎良,刘先生,于书玲,吴旭康,余切群,吴天容,贺小艳,任亚军,苏启志,刘星,张碧,王仲,乔立营,廖海建,祁文丽,朱丹,王恒洁,张女士,崔藏壑,刘女士,王胜凯,王旭,佟女士,女士,胡女士,彭女士,李婷婷,刘先生,许女士,张女士,魏静,翟成芳,蒋女士,马萱萱,陈女士,杨女士,李先生,黄女士,李女士,吕女士,程女士,牛女士,林女士,于先生,马女士,梁女士,程朝阳,张先生,郑女士,王女士,何先生,易女士,菲菲,邹周,李叶琳,赵女士,傅女士,魏女士,赵女士,何女士,陈女士,王女士,寸盼鑫,杨,李女士,卓慧华,张茗奕,梁女士,周先生';

        // $phone = '15944122062,13068778923,13502079453,15373410006,13516030892,15584233866,13840384567,15242047817,15232156589,15932486278,18830183600,13821305482,18844058288,18621788485,13946113664,18602207131,18602459075,18640950329,15373031625,13015408868,13648098493,13577038756,13820508982,15969673578,19823599288,17831137623,15723275788,13613488786,17367821553,15523324888,18677154728,13012259509,19888776650,13722242555,18227084187,15882195394,15735013333,18180905768,18222915408,18937193718,15047657985,13608845699,18103568658,15911742894,17696058054,18678859877,15923285468,13759514245,15574555355,18996221749,18763972900,15697900000,13752651276,15388741813,19977136261,18996479935,15935121985,13630816848,17376343967,18526469469,15069117282,13983147131,13180586444,18585724981,13627884888,19873902490,15103745337,15726711806,17603419099,18231652999,15331717275,18039666975,13854109878,15723353721,13368258156,13176695664,15683058718,18660435333,15532117768,17262398487,13896060772,13887315898,18725158542,18223012262,18388143273,15539217241,13612168181,18313830241,15398699809,15887842172,18983609083,15881237536,15508689510,15929581238,13393511561,13908862416,13969118320,13666134581,18313805072,18174116111,17823108466,17353278305,13831158011,13752212411,15065863483,13983176656,18182338333,13888194847,18660194560,13996459998,18953867319,13583183899,18510488799,18003403208,15087027564,13933885707,17726080090,15525460821,13883234054,17843802538,18401570699,19983788555,15347713236,13769015009,15828521551,13204128855,13173007312,19914833091,17828161218,18209284570,15617608928,18937199690,13840484480,13488762033,13673131269,13673388771,18910011528,18737111539,15094254565,15517166619,17645195741,18703685487,18202428300,15824823406,15822508790,13723054281,15010954183,17538611206,17812048236,18522007636,15840051048,13317809580,17762400363,19932191586,18633933586,13383312083,18435200195,15103407750,18737111539,18222387550,13593392027,18729978538,19828477391,15002497320,17631180903,15234079252,13151306936,19527712113,13558653592,15287224828,18031347781,15718024477,15188319992,13783422923,13251411522,18739065829,18710454472,15287122920,18234234970,17687367130,18077536576,13646506066,13033921102';

        // $phoneArr = explode(',',$phone);

        // $nameArr = explode(',',$name);

        // if(count($phoneArr)!=count($nameArr) ){

        //     echo '数据不对等';exit;

        // }

        // echo '共计：'.count($nameArr).'<br>';

        // $num = 0;

        // foreach ($nameArr as $key => $val){

        //     $where = [];

        //     array_push($where,['customer_name','=',$val]);

        //     array_push($where,['telephone','=','2147483647']);

        //     $res = Db::name("customer")->where($where)->count();

        //     if($res == 0){

        //         echo '客户：'.$val.'-手机号'.$phoneArr[$key].'--未查询到数据<br>';

        //     }else if($res > 1){

        //         echo '客户：'.$val.'-手机号'.$phoneArr[$key].'--存在多条数据，无法更新<br>';

        //     }else{

        //         $num ++;

        //         Db::name("customer")->where($where)->update(['telephone'=>$phoneArr[$key]]);

        //     }

        // }

        // echo('完成'.$num);exit;

    }

     /**

     * 更新客户k3和客户的余额记录入库

     */

    public function savek3andyue1()

    {

        $count = Db::name('a_k3yue_yuanbiao')->count() ?? 0;

        if ($count > 0) {

            echo '系统中数据未处理完毕,暂时无法导入<br><br><a href="http://sunburn.178590.com/return/k3yue.html">返回【更新客户k3和客户的余额信息息导入】页面1</a>';exit;

        }

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/k3yue.html">返回【更新客户k3和客户的余额信息息导入】页面1</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/k3yue.html">返回【更新客户k3和客户的余额信息导入】页面2</a>';exit;

        }

        // print_r(111);

        // exit;

        $importData = readExcelData($tmp_name);

        // print_r($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        $add = [];

        foreach($importData as $key => $val){

            $one = [];

            $one['customer_id'] = $val[0];

            $one['k3'] = $val[1];

            $one['neima'] = $val[2];

            $one['bahen_benjin'] = $val[3];

            $one['bahen_zengjin'] = $val[4];

            $one['xiangmu_benjin'] = $val[5];

            $one['xiangmu_zengjin'] = $val[6];

            array_push($add,$one);

        }

        // $num = $num + 500;

        $count = Db::name('a_k3yue_yuanbiao')->insertAll($add);

        echo '共计入库:'.$count.'条记录<br><br>';

        exit;

    }

    /**

     * 更新客户k3和客户的余额记录入库

     */

    public function savek3andyue2()

    {

        $list = Db::name('a_k3yue_yuanbiao')->limit(400)->select() ?? [];

        // print_r($importData);

        echo '本次处理：'.count($list).'条记录<br><br>';

        $logList = [];

        foreach($list as $key => $val){

            $log = [];

            $log['customer_id'] = $val['customer_id'];

            $log['status'] = '成功';

            $log['text'] = '';

            $find = Db::name('customer')->where('id','=',$val['customer_id'])->find();

            if(!$find){

              $log['status'] = '失败';

              $log['text'] = '客户id不存在';

              array_push($logList,$log);

              continue ;

            }

            $save = [

                    'king_no'=>$val['k3'],

                    'fcustId'=>$val['neima']

                ];

            $res = Db::name('customer')->where('id','=',$val['customer_id'])->update($save);

            if($res === false){

                $log['status'] = '失败';

                $log['text'] = 'k3编辑失败';

                array_push($logList,$log);

                continue ;

            }

            $cb = Db::name('customer_balance')->where('customer_id','=',$val['customer_id'])->select()->toArray();

            // print_r($cb);

            if(!$cb){

                $cbadd = [

                            [

                                'shop_id'     => $find['shop_id'],

                                'customer_id' => $val['customer_id'],

                                'balance_category_id' => 1,

                                'money' => $val['bahen_benjin'],

                                'complimentary_money' => $val['bahen_zengjin'],

                            ],

                            [

                                'shop_id'     => $find['shop_id'],

                                'customer_id' => $val['customer_id'],

                                'balance_category_id' => 2,

                                'money' => $val['xiangmu_benjin'],

                                'complimentary_money' => $val['xiangmu_zengjin'],

                            ]

                        ];

                // print_r($cbadd);exit;

                Db::name('customer_balance')->insertAll($cbadd);

            }else{

                $cbsave = [

                            1 =>    [

                                'shop_id'     => $find['shop_id'],

                                'money' => $val['bahen_benjin'] ?? 0,

                                'complimentary_money' => $val['bahen_zengjin'] ?? 0,

                                ],

                            2 =>    [

                                'shop_id'     => $find['shop_id'],

                                'money' => $val['xiangmu_benjin'] ?? 0,

                                'complimentary_money' => $val['xiangmu_zengjin'] ?? 0,

                                ]

                        ];

                $test = '';

                $a = [1=>'疤痕',2=>'项目'];

                foreach ($cb as $k => $v){

                    $res = Db::name('customer_balance')->where('id','=',$v['id'])->update($cbsave[$v['balance_category_id']]);

                    if($res === false){

                        $test = $test.$a[$v['balance_category_id']].'余额处理失败';

                    }

                }

                if(!empty($test)){

                    $log['status'] = '失败';

                    $log['text'] = $test;

                    array_push($logList,$log);

                    continue ;

                }

            }

            Db::name('a_k3yue_yuanbiao')->where('id','=',$val['id'])->delete();

            array_push($logList,$log);

        }

        $count = Db::name('a_k3yue_yuanbiao')->count();

        $res = Db::name('a_k3yue_jilu')->insertAll(array_values($logList));

        echo '剩余:'.$count.'条记录未处理<br><br>';

        // print_r($logList);

        print_r($res);

        exit;

        $url = 'http://sunburn.178590.com/crm/customer2/savek3andyue2';

        header("Location: $url");

        exit;

    }

    function getShop()

    {

        $list = Db::name('shop')->where([['status','=',1],['type','=',1]])->select();

        $num  = Db::name('a_kaxianggengxin_yuanbiao')->count();

        echo json_encode(['list'=>$list,'num'=>$num]);

        exit;

    }

    function getShopDel()

    {

        $shop_id = request()->param('shop_id');

        // print_r($shop_id);

        // exit;

        $cids = Db::name('customer')->where([['shop_id','=',$shop_id]])->column('id');

        $sids = Db::name('service')->where([['customer_id','in',$cids]])->column('id');

        // print_r($sids);exit;

        Db::name('service')->where([['id','in',$sids]])->delete();

        echo json_encode(['res'=>1]);

        exit;

    }

    function daorukaxiang2()

    {
        // echo "daorukaxiang2";
        // $tmp_name = $_FILES['file'];
        // echo "<pre>";
        // print_r($tmp_name);
        // echo "</pre>";
        // exit;

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        // print_r($importData[0]);exit;

        //

        // 获取不存在的客户数据

        $customerIdsList = array_values(array_unique(array_column($importData,'0')));

        $where = [];

        array_push($where,['id','in',$customerIdsList]);

        $customerList = Db::name("customer")->where($where)->column('id');

        if(count($customerIdsList) != count($customerList)){

            $chazhi = array_diff($customerIdsList,$customerList);

            echo '客户数据不存在'.implode(',',$chazhi).'<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        }

        //处理获取的员工数据

        $shopPersonNameList = array_values(array_unique(array_column($importData,'7')));

        $where = [];

        array_push($where,['name','in',$shopPersonNameList]);

        $shopPersonList = Db::name("shop_person")->where($where)->column('id','name');

        $shopPersonNameArray = array_values(array_keys($shopPersonList));

        $bucunzaideyuangong = "";

        if(count($shopPersonList) != count($shopPersonNameList)){

            echo '开卡人存在空，请先补充数据<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        }

        foreach ($shopPersonNameList as $key => $val){

            if(!in_array($val,$shopPersonNameArray)){

                $bucunzaideyuangong = $bucunzaideyuangong.'/'.$val;

            }

        }

        if(!empty($bucunzaideyuangong)){

            echo '员工数据不全('.$bucunzaideyuangong.')<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        }



        //处理获取的商品数据

        $goodsNameList = array_values(array_unique(array_column($importData,'2')));

        $where = [];

        array_push($where,['name','in',$goodsNameList]);

        $shopGoodsNameList = Db::name("shop_goods")->where($where)->column('id,category_id','name');

        if(count($goodsNameList) != count($shopGoodsNameList)){

            echo '商品数据不存在<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        }



        //处理获取的店铺数据

        $shopNameListB = array_values(array_unique(array_column($importData,'8')));

        $where = [];

        array_push($where,['shop_name','in',$shopNameListB]);

        $shopNameList = Db::name("shop")->where($where)->column('shop_id','shop_name');

        if(count($shopNameList) != count($shopNameListB)){

            echo '店铺数据不存在<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        }

        $type = ['按天'=>1,'按次'=>2];

        $addAll = [];

        foreach($importData as $key => $val){

            if(!in_array($val['4'],['按天','按次'])){

                echo '第'.($key+1).'行的类型错误<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

            }

            /*echo '<pre>';

            print_r($val);*/

            $one = [];

            $one['name'] = $val[2];

            $one['shop_id'] = $shopNameList[$val['8']];

            $one['customer_id'] = $val[0];

            $one['service_type'] = $type[$val['4']];

            if($one['service_type'] == 2){

                $one['num'] = $val[5];

                $one['start_time'] = 0;

                $one['end_time'] = 0;

            }else{

                $one['num'] = 0;

                $one['start_time'] = time();

                $one['end_time'] = intval(strtotime($val[6].' 00:00:00'));

            }

            $one['create_time'] = strtotime($val[1].' 00:00:00');

            $one['last_service_time'] = 0;

            $one['status'] = 1;

            $one['experience'] = 0;

            $one['kk_user_id'] = $shopPersonList[$val['7']] ?? 0;

            $one['kk_money'] = $val[3] ?? 0;

            $goods = $shopGoodsNameList[$val['2']] ?? [];

            //print_r($goods);exit;

            $one['goods_id'] = $goods['id'] ?? 0;

            $one['category_id'] = $goods['category_id'] ?? 0;

            //print_r($one);exit;

            array_push($addAll,$one);

        }



        $res = Db::name("a_kaxianggengxin_yuanbiao")->insertAll($addAll);

        echo '数据已校验'.$res.'，请返回手动操作数据入库<br><br><a href="http://sunburn.178590.com/return/gengxinkaxiang.html">返回【更细客户的卡项】页面</a>';exit;

        exit;

    }

    function kaxianggengxin()

    {

        $num  = Db::name('a_kaxianggengxin_yuanbiao')->count();

        if ($num == 0) {

            // code...

            echo json_encode(['num'=>$num]);

            exit;

        }

        $list = Db::name('a_kaxianggengxin_yuanbiao')->limit(1000)->select()->toArray();



        $addList = [];

        foreach ($list as $key => $val){

            $one = $val;

            unset($one['id']);

            array_push($addList,$one);

            Db::name('a_kaxianggengxin_yuanbiao')->where('id','=',$val['id'])->delete();

        }

        Db::name('a_kaxianggengxin_jilu')->insertAll($addList);

        Db::name('service')->insertAll($addList);

        $num  = Db::name('a_kaxianggengxin_yuanbiao')->count();

        echo json_encode(['num'=>$num]);

        exit;

    }

    function getshezhihuiyuan()

    {

        $res = Db::name('a_shezhihuiyuan_yuanbiao')->count();

        echo json_encode(['num'=>$res]);

        exit;

    }

    function daorushezhihuiyuan()

    {

         if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        // print_r(count($importData));exit;

        //

        // 获取不存在的客户数据

        $customerIdsList = array_values(array_unique(array_column($importData,'0')));

        $where = [];

        array_push($where,['id','in',$customerIdsList]);

        $customerList = Db::name("customer")->where($where)->column('id');

        if(count($customerIdsList) != count($customerList)){

            $chazhi = array_diff($customerIdsList,$customerList);

            echo '客户数据不存在'.implode(',',$chazhi).'<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

        }

        $addALl = [];

        foreach ($importData as $key => $val){

            $one = [];

            $one['customer_id'] = $val[0];

            $one['num'] = $val[1] ?? 0;

            $one['kaikashijian'] = $val[3] ?? '';

            $one['money'] = $val[2] ?? 0;

            if(empty($one['num']) || empty($one['kaikashijian'])){// ||empty($one['money'])){

                echo '第'.($key+1).'行的数据异常，请处理后重新上传<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

            }

            // if($one['money'] < 5000){

            //     echo '第'.($key+1).'行的数据异常，累计消费金额不足5000<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

            // }

            array_push($addALl,$one);

        }

        $res = Db::name("a_shezhihuiyuan_yuanbiao")->insertAll($addALl);

        echo '数据已校验'.$res.'<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

        exit;

    }



    function shezhihuiyuan()

    {

        $num  = Db::name('a_shezhihuiyuan_yuanbiao')->count();

        if ($num == 0) {

            // code...

            echo json_encode(['num'=>$num]);

            exit;

        }

        // $list = Db::name('a_shezhihuiyuan_yuanbiao')->limit(1000)->select()->toArray();

        $list = Db::name('a_shezhihuiyuan_yuanbiao')->select()->toArray();

        $ids = array_values(array_unique(array_column($list,'customer_id')));

        $where = [];

        array_push($where,['id','in',$ids]);

        $customerList = Db::name("customer")->where($where)->column('consumption','id');

        $num = 0;

        // print_r($customerList);

        // exit;

        // foreach ($customerList as $key => $val){

        //     if($val['membership_leve'] > 0){

        //         echo $val['id'].'已是会员<br>';

        //         $num ++;

        //     // }else if ($val['consumption'] > 0 &&$val['consumption'] < 5000) {

        //     //     // code...

        //     //     echo $val['id'].'累计消费金额小于5000<br>';

        //     //     $num ++;

        //     }

        // }

        // echo $num;

        // print_r($num);

        // exit;

        foreach($list as $key => $val){

            $add = $val;

            unset($add['id']);

            Db::name('a_shezhihuiyuan_jilu')->insert($add);

            Db::name('a_shezhihuiyuan_yuanbiao')->where('id','=',$val['id'])->delete();

            $money = $customerList[$val['customer_id']];

            if($money>=50000){

                $huiyuanid = 3;

            }else if($money<50000 && $money >=15000){

                $huiyuanid = 2;

            }else if($money > 0 &&$money <= 5000){

                $huiyuanid = 1;

            }else{

                continue;

            }

            $saveData = [];

            $saveData['membership_leve'] = $huiyuanid;//会员等级id

            $saveData['member_products'] = $val['num'];//购买了几个会员商品

            // $saveData['consumption'] = $val['money'];//累计消费金额

            $saveData['join_time'] = strtotime($val['kaikashijian']);//入会时间

            $saveData['be_overdue_time'] = bcadd($saveData['join_time'],bcmul($val['num'],31536000));//会员结束时间

            // print_r($saveData);

            // print_r($val['customer_id']);

            Db::name('customer')->where('id','=',$val['customer_id'])->update($saveData);//exit;

        }

        $num  = Db::name('a_shezhihuiyuan_yuanbiao')->count();

        echo json_encode(['num'=>$num]);

        exit;

    }

    function getshezhichengjiao()

    {

        $res = Db::name('a_shezhichengjiao_yuanbiao')->count();

        echo json_encode(['num'=>$res]);

        exit;

    }

    function daoruchengjiao()

    {

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/chengjiaoxinxi.html">返回【设置客户的成交】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/chengjiaoxinxi.html">返回【设置客户的成交】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        // print_r(count($importData));exit;

        //

        // 获取不存在的客户数据

        $customerIdsList = array_values(array_unique(array_column($importData,'0')));

        $where = [];

        array_push($where,['id','in',$customerIdsList]);

        $customerList = Db::name("customer")->where($where)->column('id');

        if(count($customerIdsList) != count($customerList)){

            $chazhi = array_diff($customerIdsList,$customerList);

            echo '客户数据不存在'.implode(',',$chazhi).'行的数据异常，请处理后重新上传<br><br><a href="http://sunburn.178590.com/return/chengjiaoxinxi.html">返回【设置客户的成交】页面</a>';exit;

        }

        $addALl = [];

        foreach ($importData as $key => $val){

            $one = [];

            $one['customer_id'] = $val[0];

            $one['money'] = $val[1] ?? 0;

            $one['chengjiaoshijian'] = $val[2] ?? '';

            if(empty($one['chengjiaoshijian'])){

                echo '第'.($key+1).'行的数据异常，请处理后重新上传<br><br><a href="http://sunburn.178590.com/return/chengjiaoxinxi.html">返回【设置客户的成交】页面</a>';exit;

            }

            // if($one['money'] < 5000){

            //     echo '第'.($key+1).'行的数据异常，累计消费金额不足5000<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

            // }

            array_push($addALl,$one);

        }

        $res = Db::name("a_shezhichengjiao_yuanbiao")->insertAll($addALl);

        echo '数据已校验'.$res.'<br><br><a href="http://sunburn.178590.com/return/chengjiaoxinxi.html">返回【设置客户的成交】页面</a>';exit;

        exit;

    }



    function shezhichengjiao()

    {

        $num  = Db::name('a_shezhichengjiao_yuanbiao')->count();

        if ($num == 0) {

            // code...

            echo json_encode(['num'=>$num]);

            exit;

        }

        $list = Db::name('a_shezhichengjiao_yuanbiao')->limit(1000)->select()->toArray();

        foreach($list as $key => $val){

            $add = $val;

            unset($add['id']);

            Db::name('a_shezhichengjiao_jilu')->insert($add);

            Db::name('a_shezhichengjiao_yuanbiao')->where('id','=',$val['id'])->delete();

            if($val['money']>=50000){

                $huiyuanid = 3;

            }else if($val['money']<50000 && $val['money'] >=15000){

                $huiyuanid = 2;

            }else{

                $huiyuanid = 1;

            }

            $saveData = [];

            $saveData['cj_money'] = $val['money'];

            $saveData['cj_time'] = strtotime($val['chengjiaoshijian']);

            Db::name('customer')->where('id','=',$val['customer_id'])->update($saveData);

        }

        $num  = Db::name('a_shezhichengjiao_yuanbiao')->count();

        echo json_encode(['num'=>$num]);

        exit;

    }

        function getgengxinxiangce()

    {

        $res = Db::name('a_gengxinxiangce_yuanbiao')->count();

        echo json_encode(['num'=>$res]);

        exit;

    }

    function daorugengxinxiangce()

    {

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/gengxinxiangce.html">返回【更新客户的相册】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/gengxinxiangce.html">返回【更新客户的相册】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);

        echo '表格中共计：'.count($importData).'条记录<br><br>';

        // print_r($importData[0]);exit;

        // $namelist = array_values(array_unique(array_column($importData,'5')));

        // $where = [];

        // array_push($where,['shop_name','in',$namelist]);

        // $shopNameList = Db::name("shop")->where($where)->column('shop_id','shop_name');

        // // print_r($shopNameList);exit;

        // foreach ($importData as $key => $val){

        //     $shop_id = $shopNameList[$val[5]] ?? 0;

        //     if($shop_id == 0){

        //         echo '0<br>';

        //         continue;

        //     }

        //     $where = [];

        //     array_push($where,['shop_id','=',$shop_id]);

        //     array_push($where,['telephone','=',$val[6]]);

        //     $id = Db::name("customer")->where($where)->value('id') ?? 0;

        //     // print_r($id);exit;

        //     echo $id.'<br>';

        // }

        // exit;

        //

        // 获取不存在的客户数据

        $customerIdsList = array_values(array_unique(array_column($importData,'0')));

        $where = [];

        array_push($where,['id','in',$customerIdsList]);

        $customerList = Db::name("customer")->where($where)->column('id');

        if(count($customerIdsList) != count($customerList)){

            $chazhi = array_diff($customerIdsList,$customerList);

            // echo '客户数据不存在'.implode(',',$chazhi).'<br><br><a href="http://sunburn.178590.com/return/gengxinxiangce.html">返回【更新客户的相册】页面</a>';exit;

        }

        $bahenleixinglist = array_values(array_unique(array_column($importData,'1')));

        $bahenbuweilist = array_values(array_unique(array_column($importData,'2')));

        $bahenchengyinlist = array_values(array_unique(array_column($importData,'3')));

        $bahenall = array_values(array_unique(array_merge($bahenleixinglist,$bahenbuweilist,$bahenchengyinlist)));

        $bahenList = Db::name("setting")->where('name','in',$bahenall)->column('id','name');

        $bahenListKey = array_keys($bahenList);

        foreach ($bahenall as $key => $val){

            if(!in_array($val,$bahenListKey)){

                $add = [

                        'name'        => $val,

                        'category_id' => 2,

                        'status'      => 1,

                        'create_time' => time(),

                        'update_time' => time(),

                    ];

                    // print_r($add);exit;

                Db::name("setting")->insert($add);

                // echo $val.'不存在，请处理后重新上传<br><br><a href="http://sunburn.178590.com/return/gengxinxiangce.html">返回【更新客户的相册】页面</a>';exit;

            }

        }

        // exit;

        $addALl = [];

        foreach ($importData as $key => $val){

            $one = [];

            $one['customer_id'] = $val[0];

            $one['bahenleixing'] = $bahenList[$val[1]] ?? 0;

            $one['bahenbuwei'] = $bahenList[$val[2]] ?? 0;

            $one['bahenchengyin'] = $bahenList[$val[3]] ?? 0;

            $one['url'] = $val[4] ?? '';

            if(empty($one['bahenleixing']) ||empty($one['bahenbuwei'])||empty($one['bahenchengyin'])||empty($one['url'])){

                echo '第'.($key+1).'行的数据异常，请处理后重新上传<br><br><a href="http://sunburn.178590.com/return/gengxinxiangce.html">返回【更新客户的相册】页面</a>';exit;

            }

            // if($one['money'] < 5000){

            //     echo '第'.($key+1).'行的数据异常，累计消费金额不足5000<br><br><a href="http://sunburn.178590.com/return/shezhihuiyuan.html">返回【设置客户的会员】页面</a>';exit;

            // }

            array_push($addALl,$one);

        }

        $res = Db::name("a_shezhihuiyuan_yuanbiao")->insertAll($addALl);

        echo '数据已校验'.$res.'<br><br><a href="http://sunburn.178590.com/return/gengxinxiangce.html">返回【更新客户的相册】页面</a>';exit;

        exit;

    }

    function shezhigengxinxiangce()

    {

        $num  = Db::name('a_gengxinxiangce_yuanbiao')->count();

        if ($num == 0) {

            // code...

            echo json_encode(['num'=>$num]);

            exit;

        }

        $list = Db::name('a_gengxinxiangce_yuanbiao')->limit(1000)->select()->toArray();

        $addAll = [];

        foreach($list as $key => $val){

            $add = $val;

            unset($add['id']);

            Db::name('a_gengxinxiangce_jilu')->insert($add);

            Db::name('a_gengxinxiangce_yuanbiao')->where('id','=',$val['id'])->delete();

            $src = $val['url'];

            $urlArr = explode(',',$src);

            foreach ($urlArr as $k => $v){

                $one = [];

                $one['customer_id'] = $val['customer_id'];

                $one['src'] = $v;

                $one['scar_type_id'] = $val['bahenleixing'];

                $one['more_id'] = $val['bahenbuwei'];

                $one['cause_of_formation_id'] = $val['bahenchengyin'];

                $one['user_id'] = 1;

                $one['create_time'] = time();

            }

        }

        Db::name('customer_album')->insertAll($addAll);

        $num  = Db::name('a_gengxinxiangce_yuanbiao')->count();

        echo json_encode(['num'=>$num]);

        exit;

    }

    function daochuchengjiaokehu()

    {

        //echo '进入2525'.'<br/>';

        $where = [];

        $newOrderWhere = [];

        $beginThismonth = $_GET['ks'] ?? '';

        $endThismonth = $_GET['js'] ?? '';

        if($endThismonth == '' || $beginThismonth == ''){

            echo '请设置开始时间和结束时间';exit;

        }

        $endThismonth = strtotime($endThismonth.' 23:59:59');

        $beginThismonth = strtotime($beginThismonth);

        // print_r($beginThismonth);exit;

        array_push($newOrderWhere,['deal_time','>=',$beginThismonth]);

        array_push($newOrderWhere,['deal_time','<=',$endThismonth]);

        array_push($newOrderWhere,['order_type','=',1]);

        array_push($newOrderWhere,['pay_amount','>=',500]);

        array_push($newOrderWhere,['type','=',3]);

        // if($shopIds){

        //     array_push($newOrderWhere,['shop_id','in',$shopIds]);

        // }

        // print_r($newOrderWhere);exit;

        $newOrderCustomerIds = Db::name("shop_refund_order") -> where($newOrderWhere) -> group('uid') -> column('uid');

        if ($newOrderCustomerIds) {

            $newOrderCustomerIds = array_values(array_unique($newOrderCustomerIds));

            array_push($where,['id','in',$newOrderCustomerIds]);

        }

       /* echo '<pre>';

        print_r($newOrderWhere);exit;

        echo '</pre>'; */

        $list = Db::name("customer")->where($where)->select()->toArray();

        if (empty($list)) {

            print_r("暂无数据");exit;

        }

        $shopId         = array_values(array_unique(array_column($list, 'shop_id')));

            $nurseId        = array_values(array_unique(array_column($list, 'nurse_id')));

            $operatorIds       = array_values(array_unique(array_column($list, 'operator')));

            //获取店铺数据

            $shopList       = Db::name('shop')->where('shop_id', 'in', $shopId)->column('shop_name,market_name', 'shop_id');

            //获取员工数据

            $personList     = Db::name('shop_person')->where('id', 'in', $nurseId)->column('name', 'id');

            //获取会员等级

            $gradeList      = Db::name('customer_grade')->column('name', 'id');

            $adminList      = Db::name('admin_user')->where('id', 'in', $operatorIds)->column('realname', 'id');

            //基础配置

            $settingList    = Db::name('setting')->column('name', 'id');

            $sexArr         = ['0' => '未知', '1' => '男', '2' => '女'];

            $EntryArr       = ['1' => '是', '2' => '否'];

            //疤痕初始化搜索

            foreach($list as $key => $val){

                if ($val['birthday']) {

                    $setData            = array();

                    $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']));

                    $setData['id']      = $val['id'];

                    $saveAll[]          = $setData;

                    $list[$key]['age']  = $setData['age'];

                }

            }




            foreach ($list as $key => $val) {

                $list[$key]['sex']             = $sexArr[$val['sex']] ?? '未知';

                $list[$key]['effective_entry'] = $EntryArr[$val['effective_entry']] ?? '未知';

                $list[$key]['shop_name']       = $shopList[$val['shop_id']]['shop_name'] ?? '';

                $list[$key]['market_name']       = $shopList[$val['shop_id']]['market_name'] ?? '';

                $list[$key]['birthday']        = $val['birthday'] ? date('Y-m-d', $val['birthday']) : '';

                $list[$key]['source_name']     = $settingList[$val['source_id']] ?? '';

                // 进店-进店时间-进店状态1未进店2已进店

                $list[$key]['first_time']      = $val['first_time']?date('Y-m-d H:i',$val['first_time']):'';

                $list[$key]['new_join_shop_time']      = $list[$key]['first_time'];

                $list[$key]['final_consumption'] = $val['final_consumption'] ? date('Y-m-d H:i',$val['final_consumption']) : '';

                $list[$key]['final_service'] = $val['final_service'] ? date('Y-m-d H:i',$val['final_service']) : '';

                $list[$key]['last_kftime'] = $val['last_kftime'] ? date('Y-m-d H:i',$val['last_kftime']) : '';

                // if ($val['be_overdue_time'] > 0){

                //     if($val['be_overdue_time'] >time()){

                //         $list[$key]['huiyuan_status'] = '生效中';

                //         if(($val['be_overdue_time']-$huiyuan_chadianguoqi_time) <=time()){

                //             $list[$key]['huiyuan_status'] = '即将过期';



                //         }

                //     }else{

                //         $list[$key]['huiyuan_status'] = '已过期';

                //     }

                // }else{

                //     $list[$key]['huiyuan_status'] = '非会员';

                // }

                $list[$key]['be_overdue_time'] = $val['be_overdue_time'] ? date('Y-m-d H:i',$val['be_overdue_time']) : '';

                $list[$key]['first_status']    = $val['first_time'] ? '1' : '2' ;

                // 会员分类-分类id-分类名称

                $list[$key]['class_name']      = $settingList[$val['member_classification']] ?? '';

                // 会员等级

                $list[$key]['grade_name']      = $gradeList[$val['membership_leve']] ?? '';

                // 负责人名称

                $list[$key]['nurse_name']      = $personList[$val['nurse_id']] ?? '';

                // 修复进展

                $list[$key]['progress_name']   = $settingList[$val['repair_progress']] ?? '';

                // 客户疤痕内容

                // $whereLogic  -> setWhereType($whereType);

                // $where       = $whereLogic -> getWhere($request,$whereType);

                // $dataCount   = $this->where($where)->count();

                $scarList    = Db::name('customer_scar')

                             ->where('customer_id','=',$val['id'])

                             ->group('customer_setting_id_type')

                             ->select()->toArray();

                $scar_aggregate          = '';

                if ($scarList){

                    $typeIdArr           = array_column($scarList, 'customer_setting_id_type');

                    foreach ($typeIdArr as $typeK => $typeV){

                        if (isset($settingList[$typeV])){

                            $scar_aggregate .= $settingList[$typeV].',';

                        }

                    }

                }

                $list[$key]['scar_aggregate']        = $scar_aggregate;

                // 客户的名称

                $list[$key]['customer_service_name'] = $adminList[$val['operator']] ?? '';

                // 成交时间

                $list[$key]['cj_time'] = $val['cj_time'] ? date('Y-m-d H:i:s',$val['cj_time']) : '' ;

                $list[$key]['cj_money'] = $val['cj_money'];

                $list[$key]['customer_name_phone'] = $val['customer_name'].'/'.$val['telephone'];

            }

        // }
		// echo '<pre>';
  //       print_r($list);exit;

        $callName = [

                    'cj_time'   =>'成交时间',

                    'customer_name' =>'姓名',

                    'telephone'=>'手机号',

                    'market_name'     =>'市场',

                    'shop_name'   =>'店面',

                    'nurse_name'    =>'负责人',

                    'cj_money'      =>'成交金额',

                    'progress_name'      =>'修复进展',

                    'grade_name'      =>'会员等级',

					'be_overdue_time'      =>'会员到期时间',

                    'scar_aggregate'      =>'疤痕类型',

                ];

        $downUrl = exportExcelData('客户明细',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";

        // return resultArray(['data' =>['url' => 'http://'.$_SERVER['HTTP_HOST'].$downUrl],'error' => '获取成功']);

    }

    public function daoruanli()

    {

        $num  = Db::name('a_anli_yu')->count();

        if($num == 0){

            echo '剩余：'.$num.'条，执行完毕';exit;

        }

        $list = Db::name('a_anli_yu')->limit(1000)->select()->toArray();

        $leixing         = array_values(array_unique(array_column($list, 'leixing')));

        $buwei         = array_values(array_unique(array_column($list, 'buwei')));

        $chengyin         = array_values(array_unique(array_column($list, 'chengyin')));

        $set = array_values(array_unique(array_merge($leixing,$buwei,$chengyin)));

        $settingList    = Db::name('setting')->where('name','in',$set)->column('id','name');

        $uids         = array_values(array_unique(array_column($list, 'uid')));

        $customerList = Db::name('customer')->where('id','in',$uids)->column('id,shop_id,nurse_id','id');

        foreach($list as $key => $val){

            $add = $val;

            unset($add['id']);

            Db::name('a_anli_jl')->insert($add);

            Db::name('a_anli_yu')->where('id','=',$val['id'])->delete();

            $leixing_id = $settingList[$val['leixing']] ?? 0;

            $buwei_id = $settingList[$val['buwei']] ?? 0;

            $chengyin_id = $settingList[$val['chengyin']] ?? 0;

            if($leixing_id == 0 || $buwei_id == 0 || $chengyin_id == 0){

                continue ;

            }

            $cu = $customerList[$val['uid']] ?? [];

            if(empty($cu)){

                continue ;

            }

            $num ++;

            $add = [

                    'shop_id'       =>$cu['shop_id'],

                    'customer_id'   =>$cu['id'],

                    'position_id'   =>$leixing_id,

                    'position_name' =>$val['leixing'],

                    'reason_id'     =>$buwei_id,

                    'reason_name'   =>$val['buwei'],

                    'type_id'       =>$chengyin_id,

                    'type_name'     =>$val['chengyin'],

                    'create_time'   =>time(),

                    'nurse_id'      =>$cu['nurse_id'],

                    'sp_excellent_time'=>time(),

                    'tg_excellent_time'=>time(),

                    'effect_results'=>3,

                    'case_results'  =>1,

                    'reviewer_id'   =>1,

                    'telephone_selection'=>1,

                    'telephone_time'     =>time(),

                    'selection_results'  =>$val['type'] == 2 ? 2:3,

                    'sqr_id'        =>$cu['nurse_id'],

                    'sq_type'       =>$val['type'] == 2 ? 1:2 ,

                ];

            $id = Db::name('case')->insertGetId($add);

            $addLog = [

                    'case_id'=>$id,

                    'images'=>$val['tupian'],

                    'create_time'=>time(),

                    'user_id'=>1

                ];

            Db::name('case_log')->insertGetId($addLog);

        }

        $num  = Db::name('a_anli_yu')->count();

        echo '剩余：'.$num.'条，继续执行中，请勿操作页面';



        echo "<script language='javascript'>";

        echo " location='https://sunburn.178590.com/crm/customer2/daoruanli';";

        echo "</script>";

        exit;

    }



    function daochujindian()

    {

        $first_time_start = '1645977600';

        $first_time_end = '1646582399';

        // $where = [];

        // array_push($where,['create_time','>=',$stime]);

        // array_push($where,['create_time','<=',$etime]);

        $customerList = Db::name('customer')

                        ->where(function ($query) use ($first_time_start,$first_time_end) {

                                $firwhere = [];

                                $twowhere = [];

                                // $first_time_start = empty($first_time_start) ? 0 : strtotime($first_time_start);

                                if($first_time_start > 0){

                                    array_push($firwhere,['first_time','>=',$first_time_start]);

                                    array_push($twowhere,['second_time','>=',$first_time_start]);

                                }

                                // $first_time_end = empty($first_time_end) ? 0 : strtotime($first_time_end);

                                if($first_time_end > 0){

                                    array_push($firwhere,['first_time','<=',$first_time_end]);

                                    array_push($twowhere,['second_time','<=',$first_time_end]);

                                }

                                if(!empty($firwhere)){

                                    $query->where(function ($query) use ($firwhere){

                                        $query->where($firwhere);

                                    });

                                    $query->whereOr(function ($query) use ($twowhere){

                                        $query->where($twowhere);

                                    });

                                }

                        })

        ->column('id,shop_id,customer_name,sex,age,telephone,source_id');

        if(empty($customerList)){

            echo '暂无导出数据';exit;

        }

        $ids = array_values(array_unique(array_column($customerList,'id')));

        $shop_ids = array_values(array_unique(array_column($customerList,'shop_id')));

        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shopList = Db::name('shop')->where($where)->column('shop_name','shop_id');

        $where = [];

        array_push($where,['category_id','=',4]);

        $laiyuanList = Db::name('setting')->where($where)->column('name','id');

        $sexList = [0=>'未知',1=>'男',2=>'女'];

        $where = [];

        array_push($where,['customer_id','in',$ids]);

        $kefangList = Db::name('return_vist')->where($where)->column('customer_id');

        $list = [];

        foreach($customerList as $key => $val){

            $one = [];

            $one['customer_name'] = $val['customer_name'];

            $one['sex'] = $sexList[$val['sex']];

            $one['shop_name'] = $shopList[$val['shop_id']];

            $one['age'] = $val['age'];

            $one['telephone'] = $val['telephone'];

            $one['source_name'] = $laiyuanList[$val['source_id']] ?? '未知';

            $one['is_kefang'] = in_array($val['id'],$kefangList) ? '是' : '否';

            array_push($list,$one);

        }

         $callName = [

                    'customer_name'   =>'姓名',

                    'shop_name' =>'门店',

                    'sex' =>'性别',

                    'age'=>'年龄',

                    'telephone'     =>'手机号',

                    'source_name'   =>'来源',

                    'is_kefang'    =>'是否回访'

                ];

        $downUrl = exportExcelData('客户明细',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";

    }



    function daochutianjia()

    {



        $where = [];

		array_push($where,['member_label','=',595]);

        $customerList = Db::name('customer')->where($where)->column('id,shop_id,customer_name,sex,age,telephone,source_id,first_time,second_time,operator,remarks,nurse_id,member_label');
		echo count($customerList);exit;
        if(empty($customerList)){

            echo '暂无导出数据';exit;

        }

        $ids = array_values(array_unique(array_column($customerList,'id')));

        $shop_ids = array_values(array_unique(array_column($customerList,'shop_id')));

        $nurse_ids = array_values(array_unique(array_column($customerList,'nurse_id')));
        //$nurse_ids2 = array_values(array_unique(array_column($customerList,'nurse_id_two')));

        $where = [];

        array_push($where,['shop_id','in',$shop_ids]);

        $shopList = Db::name('shop')->where($where)->column('shop_name','shop_id');

        // print_r($shopList);exit;

        $where = [];

        array_push($where,['id','in',$nurse_ids]);
        //array_push($where,['id','in',$nurse_ids2]);

        $shop_personList = Db::name('shop_person')->where($where)->column('name','id');
        //$shop_personList2 = Db::name('shop_person')->where($where)->column('name','id');

        //
        $where = [];

        array_push($where,['category_id','=',4]);

        $laiyuanList = Db::name('setting')->where($where)->column('name','id');

        $sexList = [0=>'未知',1=>'男',2=>'女'];

        $where = [];

        array_push($where,['customer_id','in',$ids]);

        $kefangList = Db::name('return_vist')->where($where)->column('customer_id');

        $kefuList = Db::name('admin_user')->column('realname','id');


        $list = [];

        foreach($customerList as $key => $val){

            $one = [];

            $one['customer_name'] = $val['customer_name'];

            $one['sex'] = $sexList[$val['sex']];

            $one['shop_name'] = $shopList[$val['shop_id']] ?? '';

            // print_r($shopList);exit;

            $one['nurse_name'] = $shop_personList[$val['nurse_id']] ?? '';

            $one['age'] = $val['age'];

            $one['remarks'] = $val['remarks'];

            $one['telephone'] = $val['telephone'];

            $one['source_name'] = $laiyuanList[$val['source_id']] ?? '未知';

            $one['is_kefang'] = in_array($val['id'],$kefangList) ? '是' : '否';

            $one['operator'] = $kefuList[$val['operator']] ?? '';

            $one['first_time'] = $val['first_time'] > 0 ? date('Y-m-d H:i:s',$val['first_time']) : '未进行一次进店';

            $one['second_time'] = $val['second_time'] > 0 ? date('Y-m-d H:i:s',$val['second_time']) : '未进二次进店';

            $one['member_label'] = $val['member_label'];

            // print_r($one['first_time']);

            array_push($list,$one);

        }

        /*print_r($list);

        exit;*/



        $callName = [

                    'customer_name'   =>'姓名',

                    'shop_name' =>'门店',

                    'operator' =>'客服',

                    'nurse_name' =>'护理师',

                    'sex' =>'性别',

                    'age'=>'年龄',

                    'telephone'     =>'手机号',

                    'source_name'   =>'来源',

                    'is_kefang'    =>'是否回访',

                    'remarks'    =>'备注',

                    'first_time'    =>'首次进店',

                    'second_time'    =>'二次进店',

                ];

        $downUrl = exportExcelData('客户明细',$callName,$list,'xlsx',1);
       // $downUrl = exportExcelData('核销记录',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";

    }



    function gengxinnianling()

    {

        $type  = $_GET['type'] ?? 0;

        if($type == 1){

            echo "处理完毕";

        }else{

            $page  = $_GET['page'] ?? 1;

            $limit = $_GET['limit'] ?? 2000;

            $paging['page']  = $page;

            $paging['limit'] = $limit;

            $where = [];

            $customerList = Db::name('customer')

                            ->limit(($paging['page'] - 1) * $paging['limit'], $paging['limit'])

                            ->select()->toArray();

            $page = $page + 1;

            if (empty($customerList)) {

                // code...

                $downUrl = "http://8.142.186.111/crm/customer2/gengxinnianling?page=$page&type=1";

            }else{

                foreach($customerList as $key => $val){

                    $setData            = array();

                    if ($val['birthday']>0) {

                        $setData['age']     = bcsub(date('Y'),date('Y',$val['birthday']));

                    }else{

                        $setData['age']     = 0;

                    }

                    Db::name('customer')->where('id','=',$val['id'])->update($setData);

                }

                $downUrl = "http://8.142.186.111/crm/customer2/gengxinnianling?page=$page&type=0";

                echo "本次处理：".count($customerList).'('.$customerList[0]['id'].'-'.$customerList[count($customerList)-1]['id'].')';

            }



            // print_r(Db::name('customer')->getLastSql());exit;

            echo "<script language='javascript'>";

            echo " location='".$downUrl."';";

            echo "</script>";

        }



    }

	public function serviceCardList(){
		echo '服务卡项的数据从v是';
	}




}

